﻿using System;
using System.IO;
using System.Collections.Generic;

namespace ThreeDContentPipeline
{
    public class ContentImporterContext
    {
        private Dictionary<Type, IContentTypeWriter> _ContentTypeWriters;

        public ContentImporterContext(string outputDirectory)
        {
            _ContentTypeWriters = new Dictionary<Type, IContentTypeWriter>();
            OutputDirectory = outputDirectory;
        }

        public string OutputDirectory
        {
            get;
            private set;
        }

        public string AssetName
        {
            get;
            private set;
        }

        public void AddContentTypeWriter(Type type, IContentTypeWriter typeWriter)
        {
            _ContentTypeWriters.Add(type, typeWriter);
        }

        public IContentTypeWriter GetContentTypeWriterForType(Type type)
        {
            while (type != null)
            {
                if (_ContentTypeWriters.ContainsKey(type))
                {
                    return _ContentTypeWriters[type];
                }
                type = type.BaseType;
            }
            return null;
        }

        public void Import<T>(ExternalReference reference, ContentImporter<T> importer)
        {
            ImportObject(reference, importer);
        }

        public void ImportObject(ExternalReference reference, IContentImporter importer)
        {
            string file = Path.Combine(OutputDirectory, reference.OutputFile);

            if (!File.Exists(file))
            {
                string assetName = AssetName;

                AssetName = reference.AssetName;
                WriteObject(importer.ImportObject(reference.File, this), reference);
                AssetName = assetName;
            }
        }

        private void WriteObject(object value, ExternalReference reference)
        {
            string file = Path.Combine(OutputDirectory, reference.OutputFile);

            if (!File.Exists(file))
            {
                string directory = Path.GetDirectoryName(file);

                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                ContentWriter writer = null;

                try
                {
                    writer = new ContentWriter(file, this);
                    writer.WriteAnyObject(value);
                }
                finally
                {
                    if (writer != null)
                    {
                        writer.Close();
                    }
                }
            }
        }
    }
}
